package com.lala.rennigou.controller;


import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.lala.rennigou.Util.util;
import com.lala.rennigou.pojo.EasybuyOrder;
import com.lala.rennigou.service.EasybuyOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class PayController {

    @Autowired
    private EasybuyOrderService easybuyOrderService;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    private final String APP_ID = "2021000117625137";
    private final String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC1sMjt0yQgHAFrzj7Og9QBjNZfPLTPGyjPgraAHb3DdYVEb8WtIN3gCFY9MZDWwAzjqSoIM53R0MGIMbxijyrOYuHzJ/Pj48CBgJ19WkYpLyOUgd5hJr9oSNJys0Dp/oFrNvXz16O2HoTJTrasuhflnr7DygIttFd2pYxmVF9GEjinarlRS0PvuP8QBxVzdf4gKLb1vCsjIcJmQstL0iTTW5O2PIbA0Xjpewicsiz199KItqxrIlEAF5koAwpJdc2btnsVqvy4sGrD91BzOc3zm2pGSvmu0+CJqQsO5pRcAME7NK+91PVAtTmM7tq5FOuFTApHVAT9D5F9IavMhDtLAgMBAAECggEAGwkrXPhGL+D69SfDgMdtDK4AWDuYTBkmgXpZ3caPLj6WjhBzwcdaPLQA4So2+z2orVfGwWGs4kPGCJYeCixzmjJsnNodGJQTWTHiPXzpY8d36+lHRf2WDdaIOjkiN69/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rvcCOrBxdB4le8EPMn";
    private final String CHARSET = "UTF-8";
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsTct3bwNN2AgvdwJNh+sqEbt+jr3Qcec5+Udp/ti6CUIblmN+us7OenBmtnnwUkqNw/KgiwU1AIsqAU7rBIsFyqQS454RtRUkA1ZEZUMWw/jJovU7y2J3IptWJaoBa64Vn+XsvpQL5rvwNvVah+aTTSHe597D7wIQ4btsiywoLKLJkpm2113fRpfG29IMKtHlAyPIUxM/hKQJ3t4rordfakS8CS+OecIYdfzJhOIeYOtEuAvnnFlRKFc78/pFGUGtpoBDdXE+EsOq3Tc/GEUuB7rvFZf7sL+698B2B1kIQG7aSAzHTtbc5CHC8sPO34N3+2MUYRWkJejosF0jwLSgQIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://127.0.0.1/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
//    private final String RETURN_URL = "http://127.0.0.1/returnUrl";

    private final String RETURN_URL ="http://localhost:7777/BuyCar_Two.html?lala=付款成功";

    @RequestMapping("/aliapy")
    public void alipay(HttpServletResponse httpResponse,String prices,String idz) throws IOException {

        SecureRandom r= new SecureRandom();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL+"&idz="+idz+"&prices="+prices+"&out="+out_trade_no);
        request.setNotifyUrl(NOTIFY_URL);


        //付款金额，必填
//        String total_amount =Integer.toString(r.nextInt(9999999)+1000000);
        String total_amount=prices;
        //订单名称，必填
//        String subject ="奥迪A8 2021款 A8L 60 TFSl quattro豪华型";
        String subject="购物车商品";
        //商品描述，可空
//        String body = "尊敬的会员欢迎购买奥迪A8 2021款 A8L 60 TFSl quattro豪华型";
        String body="";
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
//        return JSONArray.toJSON(form);
    }

    @RequestMapping("/out")
    public Object out(int id)  {
        EasybuyOrder easybuyOrder = easybuyOrderService.selectById(id);
//        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL,APP_ID,APP_PRIVATE_KEY,"json","UTF-8",ALIPAY_PUBLIC_KEY,"RSA2");

        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        Map map=new HashMap();
        map.put("refund_amount",easybuyOrder.getCost());
        map.put("out_trade_no",easybuyOrder.getSerialnumber());
        request.setBizContent(JSONArray.toJSONString(map));
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        Map<String ,Object> map1=new HashMap<>();
        if(response.isSuccess()){
            System.out.println("调用成功");
            easybuyOrderService.tuikuan(id);
            map1.put("msg","退款成功");
        } else {
            System.out.println("调用失败");
            map1.put("msg","退款失败");
        }
        return JSONArray.toJSON(map1);
    }

    @RequestMapping("/duanxin")
    public void duanxin(String phone,String loginName){
        String testUsername = "lytao"; //在短信宝注册的用户名
        String testPassword = "qq990826"; //在短信宝注册的密码
        String testPhone = phone;
        String testContent = "【任你购】您的验证码是【"+util.a+"】,2分钟内有效。若非本人操作请忽略此消息。"; // 注意测试时，也请带上公司简称或网站签名，发送正规内容短信。千万不要发送无意义的内容：例如 测一下、您好。否则可能会收不到
        redisTemplate.opsForValue().set(loginName+"yzm",util.a,2, TimeUnit.MINUTES);
        String httpUrl = "http://api.smsbao.com/sms";

        StringBuffer httpArg = new StringBuffer();
        httpArg.append("u=").append(testUsername).append("&");
        httpArg.append("p=").append(util.md5(testPassword)).append("&");
        httpArg.append("m=").append(testPhone).append("&");
        httpArg.append("c=").append(util.encodeUrlString(testContent, "UTF-8"));

        String result = util.request(httpUrl, httpArg.toString());
        System.out.println(result);
    }

}

